<?php
/**
 * Short Cut screen to add a mailbox to hive 
 * from the widget box
 * 
 * @author Xavier Vilain
 * @package Hive\Message
 * @license #hive-messaging#
 */

use Fox\Generator;
use Orx\User\MailBox;
use Hive\Customizing;
use Fox\Html\Button\Help;
use Fox\Html\CheckBox;
use Fox\Html\Button;
use Fox\Html\Input;
use Fox\Html\Screen;

$xview = Xview::instance();
$hostnoffound = $xview->val('hostnoffound',false);
$print_mode = $xview->val('print_mode',false);
$displayServerParams = false;
$appName = Customizing::instance()->applicationName();

$screen = new Screen('sMailbox','connect');
$screen->block()->noLegend();
$screen->message(Msg(Hive::BUNDLE,Hive::MAIL_BOX_CONNECT_HELP))
		->buttons('connect')
			->label(Msg(Hive::BUNDLE,Hive::CONNECT))
			->color(Button::COLOR_WARNING);
			
$screen->block()->add(new Input('name',true,User::current()->name()))
		->size(Input::SIZE_MEDIUM);
$screen->block()->add(new Input(array('email','email_box'),true))->size(Input::SIZE_LARGE);
$screen->block()->add(new Input(array('usrnm','username'),false))->size(Input::SIZE_LARGE)
			->hidden(true);
$screen->block()->add(new Input(array('passw','password'),true))
			->inputType('password')
			->size(Input::SIZE_MEDIUM);
			
// Server / Hostnames and Ports
$screen->block()->add(new Input(array('smtp_host','smtp'),false))->size(Input::SIZE_LARGE)
			->hidden(true)
			->label('<em style="display:inline">*</em>',false,Input::LABEL_ADD_AFTER)
			->add(new Input('smtp_port',false,null))
				->labelHasPlaceHolder()
				->noLabel()
				->hidden(true);			
$screen->block()->add(new Input(array('imap_host','imap'),false))->size(Input::SIZE_LARGE)
			->hidden(true)
			->label('<em style="display:inline">*</em>',false,Input::LABEL_ADD_AFTER)
			->add(new Input('imap_port',false,null))
				->labelHasPlaceHolder()
				->noLabel()
				->hidden(true);	
$screen->block()->add(new Input(array('pop3_host','pop3'),false))->size(Input::SIZE_LARGE)
			->hidden(true)
			->label('<em style="display:inline">*</em>',false,Input::LABEL_ADD_AFTER)
			->add(new Input('pop3_port',false,null))
				->labelHasPlaceHolder()
				->noLabel()
				->hidden(true);			
// Options Keep Email Copy
$screen->block()->add(new CheckBox('keepacopy',true))
		->renderingMode(CheckBox::RMODE_LABEL_RIGHT)
		->label(Msg(Orx\Mailer\Messages::BUNDLE,
					Orx\Mailer\Messages::KEEP_A_COPY_OF_EMAIL
				))
		->helpMessage(Msg(Orx\Mailer\Messages::BUNDLE,
					Orx\Mailer\Messages::KEEP_A_COPY_OF_EMAIL_HELP,
					$appName
				));

// Options Use SLL
$screen->block()->add(new CheckBox('usessl'))
		->renderingMode(CheckBox::RMODE_LABEL_RIGHT)
		->label(Msg(Orx\Mailer\Messages::BUNDLE,
					Orx\Mailer\Messages::ALWAYS_USE_SSL
				))
		->helpMessage(Msg(Orx\Mailer\Messages::BUNDLE,
					Orx\Mailer\Messages::ALWAYS_USE_SSL_HELP
				));
$screen->block()->labelSize('100',true);
if($screen->submitted()) {
	$fields = $screen->get();
	$mailer = new MailBox();
	
	// Try to validate the email address
	$emailFormater = new Fox\Ddic\DataElement\Formater\Email();
	if(!$emailFormater->check($fields['email_box'])) {
		Fox\Message::Error(Msg(Hive::BUNDLE,Hive::EMAIL_NOT_VALID));
	}
	if(!$screen->errors()) {
		// Check Duplicates
		$res = \Fox\Dao::finder(MailBox::className())
			->where('email LIKE ?',array($fields['email_box']))
			->find();
		if(count($res) > 0) {
			Fox\Message::Error(Msg(Orx\Mailer\Messages::BUNDLE,
											Orx\Mailer\Messages::ERR_ALREADY_USED_EMAIL,
											User::fullName($res[0]->idusr)));
		}
	}
	if(!$screen->errors()) {
		if(empty($fields['imap'])) {
			// Try to find the host 
			$params = $mailer::detectParams($fields['email_box'],$fields['usessl']);
			$fields = array_merge($fields,$params);
			$screen->initialize($fields);
		} else {
			$parts = explode('@',$fields['email_box']);
			$fields['domain'] = $parts[count($parts)-1];
		}
		$fields['idusr'] = User::current()->getId();
		$fields['email'] = $fields['email_box'];
		$fields['password'] = \Fox\Utilities::crypt($fields['password'],_HIVE_PRIVATE_KEY_);
		$fields['disable'] = 0;
		$mailer->setFields($fields);
		try {
			try {
				// Test Imap Connection - for email retrieval (only count number of email for now)
				$nbMessages = $mailer->imap()->count();	
				$mailer->protocol_to_retrieve = 'imap';
			} catch(Exception $e) {
				// Test POP3 in case of imap failure
				$nbMessages = $mailer->pop3()->count();
				$mailer->protocol_to_retrieve = 'pop3';
			}
			
			$mailer->create();
			Fox\Message::Success(Msg(Orx\Mailer\Messages::BUNDLE,
					Orx\Mailer\Messages::MAILBOX_ADDED_SUCCESS,
					$appName));
			$mailer->redirect(Generator::url('messages',null,null,array('print_mode'=> $print_mode)));
		} catch(Fox\Object\Exception\Save $e) {
			$displayServerParams = true;
			\Fox\Message::Error($e);
		} catch(Exception $e) {
			switch($e->getMessage()) {
				case 'last request failed' :
					Fox\Message::Error(Msg(Orx\Mailer\Messages::BUNDLE,
											Orx\Mailer\Messages::ERR_USER_OR_PASSWORD_INVALID));
					break;
				case 'cannot login, user or password wrong':
					Fox\Message::Error(Msg(Orx\Mailer\Messages::BUNDLE,
											Orx\Mailer\Messages::ERR_USER_OR_PASSWORD_INVALID));
					break;
				default:
					if(!empty($parts)) {
						Fox\Message::Error(Msg(Hive::BUNDLE,Hive::ERROR_HOST_NOT_FOUND_FROM_EMAIL));
					} else {
						Fox\Message::Error(Msg(Hive::BUNDLE,Hive::ERROR_HOST_CANNOT_BE_REACHED));
					}
					
			}
			$displayServerParams = true;
			if(DEV_ENV) {
				var_dump($e);
			}
		}
	}
}

if($displayServerParams) {
	$screen->item('smtp')->hidden(false);
	$screen->item('smtp_port')->hidden(false);
	$screen->item('pop3')->hidden(false);
	$screen->item('pop3_port')->hidden(false);
	$screen->item('imap')->hidden(false);
	$screen->item('imap_port')->hidden(false);
	$screen->item('username')->hidden(false);
}
echo $screen->display();